// 分享详情页面
const app = getApp();

Page({
  data: {
    shareId: null,
    shareDetail: null,
    loading: true,
    comments: [],
    newComment: '',
    submittingComment: false
  },

  // 统一图片 URL 构造
  getImageUrl(imagePath) {
    const { buildMediaUrl } = require('../../../utils/media');
    return buildMediaUrl(imagePath);
  },

  // 格式化时间
  formatTime(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚';
    }
    // 小于1小时
    if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟前';
    }
    // 小于1天
    if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时前';
    }
    // 超过1天
    return date.toLocaleDateString('zh-CN');
  },

  onLoad(options) {
    console.log('分享详情页面加载，参数:', options);
    
    if (options.id) {
      this.setData({
        shareId: options.id
      });
      this.loadShareDetail();
      
      // 如果是从列表页面点击分享按钮跳转过来，显示分享提示
      if (options.action === 'share') {
        setTimeout(() => {
          wx.showModal({
            title: '分享提示',
            content: '请点击右上角"···"菜单，选择"转发"来分享给好友',
            showCancel: false,
            confirmText: '我知道了'
          });
        }, 500);
      }
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  async loadShareDetail() {
    try {
      wx.showLoading({ title: '加载中...' });

  // 确保 token：优先全局，其次本地缓存
  const token = app.globalData.token || wx.getStorageSync('token');
  if(!app.globalData.token && token){ app.globalData.token = token; }
  const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/social/get-share-detail`,
          method: 'GET',
          data: { share_id: this.data.shareId },
          header: {
            'Content-Type': 'application/json',
    'Authorization': token ? `Bearer ${token}` : ''
          },
          success: resolve,
          fail: reject
        });
      });

      wx.hideLoading();

      if (res.statusCode === 401) {
        wx.showToast({ title: '请先登录', icon: 'none' });
        this.setData({ loading:false });
        return;
      }
      if (res.statusCode === 200 && res.data.success) {
        const { mapMediaUrls } = require('../../../utils/media');
        const raw = res.data.data.share;
        const mapped = mapMediaUrls(raw.image_urls);
        const normalized = {
          ...raw,
          image_urls: mapped,
          images: mapped // 兼容可能的旧模板字段
        };
        console.log('详情页图片映射结果:', normalized.image_urls);
        this.setData({
          shareDetail: normalized,
          comments: res.data.data.comments || [],
          loading: false
        });

      } else {
        throw new Error(res.data.message || '加载失败');
      }
    } catch (error) {
      wx.hideLoading();
      console.error('加载分享详情失败:', error);
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },


  // 点赞
  async onLike() {
    if (!app.globalData.token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/social/toggle-like`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${app.globalData.token}`
          },
          data: { share_id: this.data.shareId },
          success: resolve,
          fail: reject
        });
      });

      if (res.statusCode === 200 && res.data.success) {
        const { is_liked, like_count } = res.data.data;
        
        this.setData({
          'shareDetail.is_liked': is_liked,
          'shareDetail.like_count': like_count
        });

        wx.showToast({
          title: is_liked ? '点赞成功' : '取消点赞',
          icon: 'success',
          duration: 1000
        });
      }
    } catch (error) {
      console.error('点赞失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  // 输入评论
  onCommentInput(e) {
    this.setData({
      newComment: e.detail.value
    });
  },

  // 提交评论
  async onSubmitComment() {
    console.log('提交评论按钮点击');
    
    if (!app.globalData.token) {
      console.log('用户未登录');
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    if (!this.data.newComment.trim()) {
      console.log('评论内容为空');
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    console.log('开始提交评论:', this.data.newComment.trim());
    this.setData({ submittingComment: true });

    try {
      console.log('发送评论请求到:', `${app.globalData.apiBaseUrl}/social/add-comment`);
      console.log('请求数据:', {
        share_id: this.data.shareId,
        content: this.data.newComment.trim()
      });

      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/social/add-comment`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${app.globalData.token}`
          },
          data: {
            share_id: this.data.shareId,
            content: this.data.newComment.trim()
          },
          success: resolve,
          fail: reject
        });
      });

      console.log('评论请求响应:', res);

      if (res.statusCode === 200 && res.data.success) {
        console.log('评论成功，响应数据:', res.data);
        // 添加新评论到当前评论列表
        const newComment = res.data.data.comment;
        const currentComments = this.data.comments || [];
        
        console.log('当前评论列表:', currentComments);
        console.log('新增评论:', newComment);
        console.log('更新后评论数量:', res.data.data.comment_count);
        
        this.setData({
          comments: [...currentComments, newComment],
          newComment: '',
          'shareDetail.comment_count': res.data.data.comment_count
        });

        console.log('页面数据更新完成，当前评论数:', this.data.comments.length);

        wx.showToast({
          title: '评论成功',
          icon: 'success'
        });
      } else {
        console.error('评论失败，状态码:', res.statusCode, '响应:', res.data);
        throw new Error(res.data.message || '评论失败');
      }
    } catch (error) {
      console.error('评论异常:', error);
      wx.showToast({
        title: error.message || '评论失败',
        icon: 'none'
      });
    } finally {
      console.log('评论提交完成，重置状态');
      this.setData({ submittingComment: false });
    }
  },

  // 分享
  onShare() {
    const shareDetail = this.data.shareDetail;
    if (!shareDetail) return;
    
    wx.showActionSheet({
      itemList: ['转发给好友', '生成分享海报'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 转发给好友 - 微信小程序不支持主动调用分享，提示用户使用右上角菜单
          wx.showModal({
            title: '转发提示',
            content: '请点击右上角"···"菜单，选择"转发"来分享给好友',
            showCancel: false,
            confirmText: '我知道了',
            success: () => {
              // 记录分享意图
              this.recordShare();
            }
          });
        } else if (res.tapIndex === 1) {
          // 生成分享海报 - 暂时用模态框提示，未来可以实现海报生成功能
          wx.showModal({
            title: '分享海报',
            content: '分享海报功能开发中，敬请期待',
            showCancel: false,
            confirmText: '知道了'
          });
        }
      }
    });
  },

  async recordShare() {
    try {
      wx.request({
        url: `${app.globalData.apiBaseUrl}/social/record-share`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': app.globalData.token ? `Bearer ${app.globalData.token}` : ''
        },
        data: { share_id: this.data.shareId }
      });
    } catch (error) {
      console.error('记录分享失败:', error);
    }
  },

  /**
   * 微信小程序分享回调 - 分享给好友
   */
  onShareAppMessage() {
    const shareDetail = this.data.shareDetail;
    if (!shareDetail) {
      return {
        title: '视力健康分享',
        path: `/pages/social/detail/detail?id=${this.data.shareId}`
      };
    }
    
    return {
      title: shareDetail.title || '视力健康分享',
      desc: shareDetail.content ? shareDetail.content.substring(0, 50) + '...' : '来看看这个有用的分享吧！',
      path: `/pages/social/detail/detail?id=${shareDetail.id}`,
      imageUrl: shareDetail.image_urls && shareDetail.image_urls.length > 0 ? 
                 shareDetail.image_urls[0] : '/images/default-share.png'
    };
  },

  /**
   * 微信小程序分享回调 - 分享到朋友圈
   */
  onShareTimeline() {
    const shareDetail = this.data.shareDetail;
    if (!shareDetail) {
      return {
        title: '视力健康分享',
        query: `id=${this.data.shareId}`
      };
    }
    
    return {
      title: shareDetail.title || '视力健康分享',
      query: `id=${shareDetail.id}`,
      imageUrl: shareDetail.image_urls && shareDetail.image_urls.length > 0 ? 
                 shareDetail.image_urls[0] : '/images/default-share.png'
    };
  },

  // 格式化时间
  formatTime(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    if (diff < 60000) return '刚刚';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
    return `${Math.floor(diff / 86400000)}天前`;
  }
});
